package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.RecommendUserQueryParam;
import com.tanhua.server.vo.TodayBest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
@Slf4j
public class TodayBestService {

    @Autowired
    private UserService userService;//校验Token用的

    @Autowired
    private RecommendUserService recommendUserService;//调dubbo用的

    @Value("${tanhua.sso.default.user}")
    private Long defaultUser;//默认佳人的id

    @Autowired
    private UserInfoService userInfoService;//查询MySQL

    public TodayBest queryTodayBest() {
        //1.通过OSS校验token
        User user = UserThreadLocal.get();
//        if (user == null){
//            log.error("token校验失败，返回对象为null");
//            return null;
//        }

        //2.查询该用户的今日佳人
        TodayBest todayBest = null;
        try{
            todayBest = recommendUserService.queryTodayBest(user.getId());
        }catch (Exception e){
            log.error("查询今日佳人ID出错"+user.getId(),e);
        }
        //如果查询出的对象为null，就给出默认的数据
        if (todayBest == null){
            todayBest = new TodayBest();
            todayBest.setId(defaultUser);
            todayBest.setFateValue(80L);
        }

        //3.查询MySQL将今日佳人信息补全
        UserInfo userInfo = userInfoService.queryUserInfoByUserId(todayBest.getId());
        if (userInfo == null){
            log.error("MySQL查询数据为null,ID："+todayBest.getId());
            return null;
        }

        todayBest.setAge(userInfo.getAge());
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man":"woman");
        todayBest.setTags(StringUtils.split(userInfo.getTags(),","));

        return todayBest;
    }

    /**
     * 查询推荐
     * @param token
     * @param queryParam 查询结果对象
     * @return
     */
    public PageResult queryRecommendation(RecommendUserQueryParam queryParam) {
        //1.通过OSS校验token
        User user = UserThreadLocal.get();
//        if (user == null){
//            log.error("token校验失败，返回对象为null");
//            return null;
//        }

        //创建PageResult对象，封装PageInfo的信息，并返回
        //PageResult -> 结果对象
        PageResult pageResult = new PageResult();
        pageResult.setPage(queryParam.getPage());
        pageResult.setPagesize(queryParam.getPagesize());

        //2.查询这个userid的所有推荐用户
        //返回一个PageInfo对象，封装了分页参数和查询出来的推荐列表的数据
        PageInfo<RecommendUser> pageInfo =
                recommendUserService.queryRecommendUserList(user.getId(),queryParam.getPage(),queryParam.getPagesize());
        //获得pageInfo中存放推荐列表信息的数据
        List<RecommendUser> records = pageInfo.getRecords();
        if (CollectionUtils.isEmpty(records)){
            //没有查询到对应的推荐列表
            return null;
        }

        //3.查询MySQL,补全信息
        //获得所有推荐用户的id,使用set集合进行去重
        Set<Long> userIds = new HashSet<>();
        //遍历存放推荐列表信息的list集合，将其中的userId存放到userIds的集合中
        for (RecommendUser record : records) {
            userIds.add(record.getUserId());
        }

        //构建query条件，用于在MySQL中查询所有推荐列表中的id的详细信息
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id",userIds);

        //查询MySQL数据
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(queryWrapper);
        if (CollectionUtils.isEmpty(userInfoList)){
            //查询结果为空
            return null;
        }

        /**
         * 目前，用户的信息再两个集合中：
         *     userInfoList：MySQL的userInfo表中的用户具体信息
         *     records：MongoDB的recommend_user表中的用户缘分值
         * 所以下面需要整合两个集合的数据，得到一个完整的推荐用户信息的集合
         */
        //存放推荐用户完整信息的集合
        List<TodayBest> todayBests = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            //新建对象
            TodayBest todayBest = new TodayBest();

            todayBest.setId(userInfo.getId());
            todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man":"woman");
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setTags(StringUtils.split(userInfo.getTags(),","));
            todayBest.setAge(userInfo.getAge());

            //缘分值的添加
            for (RecommendUser record : records) {
                if (todayBest.getId().longValue() == userInfo.getUserId().longValue()){
                    todayBest.setFateValue(record.getScore().longValue());
                }
            }

            //将完整的推荐用户信息的对象添加到集合中
            todayBests.add(todayBest);
        }

        //排序
        Collections.sort(todayBests, new Comparator<TodayBest>() {
            @Override
            public int compare(TodayBest o1, TodayBest o2) {
                return (o2.getFateValue().intValue())-(o1.getFateValue().intValue());
            }
        });

        //将补全信息完成的集合，封装到结果对象中
        pageResult.setItems(todayBests);
        return pageResult;
    }
}
